﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities;
using Entities.IRepository;
using BLL;
using DAL;
using System.Data.SqlClient;
using HeThongNhaSach.Report;
using System.Configuration;
using CrystalDecisions.Shared;
namespace HeThongNhaSach
{
    public partial class frmMain : DevComponents.DotNetBar.Office2007RibbonForm
    {
        SqlConnection cnn;
        string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        private GeneralRepository<HoaDon> _HDRepo;
        private QLHoaDon _HDManager;
        private GeneralRepository<CTHoaDon> _CTHDRepo;

        private GeneralRepository<NhanVien> _NVRepo;
        private QLNhanVien _NVManager;
        private GeneralRepository<ChamCong> _CCRepo;
        private SachBaoRepository _SBRepo;
        private QLSachBao _SBManager;
        List<NhanVien> nv;
        private GeneralRepository<TaiKhoan> _TKRepo;
        private QLTaiKhoan _TKManager;
        public string user = "";
        public string pq = "";

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            cnn = new SqlConnection(connectionString);
            try
            {
                _HDRepo = new GeneralRepository<HoaDon>();
                _HDManager = new QLHoaDon(_HDRepo);
                _CTHDRepo = new GeneralRepository<CTHoaDon>();
                nv = new List<NhanVien>();
                _CCRepo = new GeneralRepository<ChamCong>();
                _NVRepo = new GeneralRepository<NhanVien>();
                _NVManager = new QLNhanVien(_NVRepo);
                _TKManager = new QLTaiKhoan(_TKRepo);
                _SBRepo = new SachBaoRepository();
                _SBManager = new QLSachBao(_SBRepo);
                _TKRepo = new GeneralRepository<TaiKhoan>();
                XuLyDangNhap();
                LoadSachBao();
                RefreshTK();
                RefreshNV();
                RefreshHD();

            }
            catch (Exception)
            {
                MessageBox.Show("Không thể kết nối tới cơ sở dữ liệu. Chạy file Connect.exe trong thư mục cài đặt phần mềm để cập nhật kết nối tới cơ sở dữ liệu");
                Application.Exit();
            }


        }

        #region Ql Hóa Đơn



        /// <summary>
        /// button thêm hóa đơn
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThemHD_Click(object sender, EventArgs e)
        {
            ThemHD frm = new ThemHD();
            frm.frmChinh = this;
            frm.ShowDialog();
        }
        /// <summary>
        /// button tim kiếm hóa đơn
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTimKiemHD_Click(object sender, EventArgs e)
        {
            TimKiemHD frm = new TimKiemHD();
            frm.frmChinh = this;
            frm.ShowDialog();
        }

        /// <summary>
        /// Làm mới danh sách hóa đơn
        /// </summary>

        public void RefreshHD()
        {
            List<HoaDon> lhd = _HDRepo.GetAll().ToList();
            lhd.Sort();
            dgvHoaDon.DataSource = lhd;
        }

        /// <summary>
        /// button làm mới danh sách
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefreshHD_Click(object sender, EventArgs e)
        {
            RefreshHD();
        }
        /// <summary>
        /// tạo sự kiện cellclick cho datagridview hóa đơn
        /// khi click vào row trên datagridview sẽ hiển thị hóa đơn cần in
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvHoaDon_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            {
                HoaDon hd = dgvHoaDon.SelectedRows[0].DataBoundItem as HoaDon;
                SqlConnection cnn;
                string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                cnn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("InHoaDon", cnn);
                cmd.Parameters.Add("@MaHoaDon", SqlDbType.NVarChar, 20).Value = hd.MaHoaDon;
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter dscmd = new SqlDataAdapter(cmd);
                DataSet1 ds = new DataSet1();
                dscmd.Fill(ds.DataTable1);
                HoaDonBH objRpt = new HoaDonBH();
                objRpt.SetDataSource(ds.Tables[0]);
                ParameterDiscreteValue pdv = new ParameterDiscreteValue();
                pdv.Value = hd.MaHoaDon;
                ParameterValues pv = new ParameterValues();
                pv.Add(pdv);
                objRpt.DataDefinition.ParameterFields["MaHoaDon"].ApplyCurrentValues(pv);
                pdv.Value = hd.NgayLap;
                pv.Add(pdv);
                objRpt.DataDefinition.ParameterFields["NgayLap"].ApplyCurrentValues(pv);
                pdv.Value = hd.MaNhanVien;
                pv.Add(pdv);
                objRpt.DataDefinition.ParameterFields["MaNhanVien"].ApplyCurrentValues(pv);
                pdv.Value = hd.ThanhTien;
                pv.Add(pdv);
                objRpt.DataDefinition.ParameterFields["ThanhTien"].ApplyCurrentValues(pv);
                pdv.Value = txtTenCH.Text;
                pv.Add(pdv);
                objRpt.DataDefinition.ParameterFields["TenCH"].ApplyCurrentValues(pv);
                crystalReportViewer1.ReportSource = objRpt;
                crystalReportViewer1.Refresh();
                DialogResult rs = MessageBox.Show("In hóa đơn", "Bạn có muốn in hóa đơn này không", MessageBoxButtons.YesNo);
                if (rs == DialogResult.Yes)
                    crystalReportViewer1.PrintReport();
            }
        }

        #endregion

        #region QL Sách Báo


        public void LoadSachBao()
        {
            datasachbao.DataSource = (new SachBaoRepository()).LayTatCa().ToList();
        }

        private void btnLoadSB_Click(object sender, EventArgs e)
        {
            LoadSachBao();
        }
        private void btnXoaSB_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in datasachbao.SelectedRows)
            {
                if (_CTHDRepo.GetAll().ToList().Find(t => t.MaSachBao == row.Cells[0].Value.ToString()) != null)
                {
                    MessageBox.Show("Đã có hóa đơn bán sách: " + row.Cells[0].Value.ToString());
                    return;
                }
                if (row.DataBoundItem is Sach)
                    _SBManager.DeleteSach(row.Cells[0].Value.ToString());
                if (row.DataBoundItem is Bao)
                    _SBManager.DeleteBao(row.Cells[0].Value.ToString());
                if (row.DataBoundItem is TapChi)
                    _SBManager.DeleteTapChi(row.Cells[0].Value.ToString());


            }
            LoadSachBao();
        }
        private void btnTimKiemSB_Click(object sender, EventArgs e)
        {
            frmTimKiem frm = new frmTimKiem();
            frm.frmMain = this;
            frm.ShowDialog();
            tabControl1.SelectedTab = tabSachBao;
        }
        private void btnCapNhatSB_Click(object sender, EventArgs e)
        {
            frmCapNhatSB capnhat = new frmCapNhatSB();
            capnhat.frmChinh = this;
            if (datasachbao.SelectedRows.Count > 0)
            {
                SachBao sb = (SachBao)(datasachbao.SelectedRows[0].DataBoundItem);
                capnhat.sb = sb;
            }
            capnhat.ShowDialog();
        }
        #endregion

        #region QL Nhân Viên


        /// <summary>
        /// làm mới danh sách nhân viên
        /// </summary>
        public void RefreshNV()
        {
            dgvNhanVien.DataSource = _NVRepo.GetAll().ToList();

        }
        private void btnLoadNhanVien_Click(object sender, EventArgs e)
        {
            RefreshNV();
        }


        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        /// <summary>
        /// button chấm công tính lương cho nhân viên
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChamCong_Click(object sender, EventArgs e)
        {
            frmChamCong frm = new frmChamCong();
            frm.ucChamCong1.btnNext.Handle.ToInt32();
            frm.ucChamCong1.btnPrev.Handle.ToInt32();
            frm.ucChamCong1.lbl1.Handle.ToInt32();
            frm.ucChamCong1.lbl2.Handle.ToInt32();
            frm.ucChamCong1.lbl3.Handle.ToInt32();
            frm.ucChamCong1.lbl4.Handle.ToInt32();
            frm.ucChamCong1.lbl5.Handle.ToInt32();
            frm.ucChamCong1.lbl6.Handle.ToInt32();
            frm.ucChamCong1.lbl7.Handle.ToInt32();
            frm.ucChamCong1.lbl8.Handle.ToInt32();
            frm.ucChamCong1.lbl9.Handle.ToInt32();
            frm.ucChamCong1.lbl10.Handle.ToInt32();
            frm.ucChamCong1.lbl11.Handle.ToInt32();
            frm.ucChamCong1.lbl12.Handle.ToInt32();
            frm.ucChamCong1.lbl13.Handle.ToInt32();
            frm.ucChamCong1.lbl14.Handle.ToInt32();
            frm.ucChamCong1.lbl15.Handle.ToInt32();
            frm.ucChamCong1.lbl16.Handle.ToInt32();
            frm.ucChamCong1.lbl17.Handle.ToInt32();
            frm.ucChamCong1.lbl18.Handle.ToInt32();
            frm.ucChamCong1.lbl19.Handle.ToInt32();
            frm.ucChamCong1.lbl20.Handle.ToInt32();
            frm.ucChamCong1.lbl21.Handle.ToInt32();
            frm.ucChamCong1.lbl22.Handle.ToInt32();
            frm.ucChamCong1.lbl23.Handle.ToInt32();
            frm.ucChamCong1.lbl24.Handle.ToInt32();
            frm.ucChamCong1.lbl25.Handle.ToInt32();
            frm.ucChamCong1.lbl26.Handle.ToInt32();
            frm.ucChamCong1.lbl27.Handle.ToInt32();
            frm.ucChamCong1.lbl28.Handle.ToInt32();
            frm.ucChamCong1.lbl29.Handle.ToInt32();
            frm.ucChamCong1.lbl30.Handle.ToInt32();
            frm.ucChamCong1.lbl31.Handle.ToInt32();
            frm.ucChamCong1.lbl32.Handle.ToInt32();
            frm.ucChamCong1.lbl33.Handle.ToInt32();
            frm.ucChamCong1.lbl34.Handle.ToInt32();
            frm.ucChamCong1.lbl35.Handle.ToInt32();
            frm.ucChamCong1.lbl36.Handle.ToInt32();
            frm.ucChamCong1.lbl37.Handle.ToInt32();
            frm.ucChamCong1.lbl38.Handle.ToInt32();
            frm.ucChamCong1.lbl39.Handle.ToInt32();
            frm.ucChamCong1.lbl40.Handle.ToInt32();
            frm.ucChamCong1.lbl41.Handle.ToInt32();
            frm.ucChamCong1.lbl42.Handle.ToInt32();

            NhanVien nv = dgvNhanVien.SelectedRows[0].DataBoundItem as NhanVien;
            frm.nv = nv;
            frm.ShowDialog();
        }


        private void btnCapNhapNV_Click(object sender, EventArgs e)
        {
            frmThemNhanVien frm = new frmThemNhanVien();
            frm.frmChinh = this;
            if (dgvNhanVien.SelectedRows.Count > 0)
            {
                NhanVien sb = (NhanVien)(dgvNhanVien.SelectedRows[0].DataBoundItem);
                frm.nv = sb;
            }
            frm.ShowDialog();
        }

        private void btnXoaNV_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dgvNhanVien.Rows)
            {
                if (row.Selected == true)
                {
                    if (_CCRepo.GetAll().ToList().Find(t => t.MaNhanVien == row.Cells[0].Value.ToString()) != null || _HDRepo.GetAll().ToList().Find(t => t.MaNhanVien == row.Cells[0].Value.ToString()) != null)
                    {
                        MessageBox.Show("Không thể xóa. Nhân viên đã được chấm công hoặc lập hóa đơn bán hàng");
                        return;
                    }
                    NhanVien nv = row.DataBoundItem as NhanVien;
                    var aResult = _NVManager.Delete(nv);
                    if (aResult.Success)
                    {
                        MessageBox.Show("Xóa thành công");
                        RefreshNV();
                    }
                    else
                        MessageBox.Show(aResult.GetErrorMessages());
                }
            }
        }

        private void btnTimKiemNV_Click(object sender, EventArgs e)
        {
            frmTimKiemNhanVien frm = new frmTimKiemNhanVien();
            frm.frmChinh = this;
            frm.ShowDialog();
        }
        #endregion

        #region QL Tài Khoản


        public void XuLyDangNhap()
        {
            if (pq == "")
            {
                btnLogin.Enabled = true;
                btnDoiPass.Enabled = false;
                //btnLoadPN.Enabled = false;

                btnLogout.Enabled = false;
                btnQLNhanVien.Enabled = false;
                
                btnNgay.Enabled = false;
                btnNam.Enabled = false;
                btnThang.Enabled = false;
                btnQLHoaDon.Enabled = false;
                btnQLSachBao.Enabled = false;
                txtTenCH.Enabled = false;
                tabHD.Visible = false;
                tabtaikhoan.Visible = false;
                btnItemQLTaiKhoan.Enabled = false;
                tabNV.Visible = false;
                tabThongKe.Visible = false;
                btnCapNhatSB.Enabled = false;
                btnXoaSB.Enabled = false;

            }
            else
            {
                btnLogin.Enabled = false;
                btnDoiPass.Enabled = true;
                //btnLoadPN.Enabled = false;
                btnNgay.Enabled = true;
                btnNam.Enabled = true;
                btnThang.Enabled = true;
                btnLogout.Enabled = true;
                btnQLNhanVien.Enabled = true;
                txtTenCH.Enabled = true;
                btnQLHoaDon.Enabled = true;
                btnQLSachBao.Enabled = true;
                tabHD.Visible = true;
                tabNV.Visible = true;
                tabtaikhoan.Visible = true;
                btnItemQLTaiKhoan.Enabled = true;
                tabThongKe.Visible = true;
                btnCapNhatSB.Enabled = true;
                btnXoaSB.Enabled = true;
                if (pq.Contains("Bán Hàng"))
                {
                    tabNV.Visible = false;
                    tabThongKe.Visible = false;
                    btnCapNhatSB.Enabled = false;
                    btnXoaSB.Enabled = false;
                    txtTenCH.Enabled = false;
                    tabHD.Visible = true;
                    btnQLNhanVien.Enabled = false;
                    tabtaikhoan.Visible = false;
                    btnItemQLTaiKhoan.Enabled = false;
                    btnitemCapNhapSB.Enabled = false;
                }
                else
                {
                    tabNV.Visible = true;
                    tabtaikhoan.Visible = true;
                    btnItemQLTaiKhoan.Enabled = true;
                    tabThongKe.Visible = true;
                    btnCapNhatSB.Enabled = true;
                    btnXoaSB.Enabled = true;
                    txtTenCH.Enabled = true;
                    tabHD.Visible = true;
                    btnQLNhanVien.Enabled = true;
                    btnitemCapNhapSB.Enabled = true;
                    if (pq.Contains("Thủ Kho"))
                    {
                        tabNV.Visible = false;
                        tabThongKe.Visible = false;
                        btnQLNhanVien.Enabled = false;
                        tabtaikhoan.Visible = false;
                        btnItemQLTaiKhoan.Enabled = false;
                        btnQLHoaDon.Enabled = false;
                        tabHD.Visible = false;
                        txtTenCH.Enabled = false;
                        btnNgay.Enabled = false;
                        btnNam.Enabled = false;
                        btnThang.Enabled = false;

                    }
                    else
                    {
                        tabNV.Visible = true;
                        tabThongKe.Visible = true;
                        btnQLNhanVien.Enabled = true;
                        tabtaikhoan.Visible = true;
                        btnItemQLTaiKhoan.Enabled = true;
                        btnQLHoaDon.Enabled = true;
                        tabHD.Visible = true;
                        txtTenCH.Enabled = true;
                        btnNgay.Enabled = true;
                        btnNam.Enabled = true;
                        btnThang.Enabled = true;

                    }
                }
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            frmLogin frm = new frmLogin();
            frm.frmMain = this;
            frm.ShowDialog();
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Bạn có muốn đăng xuất không?", "Xác nhận", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                pq = "";
                XuLyDangNhap();
            }
        }

        private void btnDoiPass_Click(object sender, EventArgs e)
        {
            frmDoiMatKhau frm = new frmDoiMatKhau();
            frm._Username = this.user;
            frm.ShowDialog();
        }
        public void RefreshTK()
        {
            datataikhoan.DataSource = _TKRepo.GetAll().ToList();
        }

        private void loadtaikhoan_Click(object sender, EventArgs e)
        {
            RefreshTK();
        }

        private void btnCapNhapTK_Click(object sender, EventArgs e)
        {
            frmQLTaiKhoan frm = new frmQLTaiKhoan();
            frm.ShowDialog();
        }

       


        #endregion

        #region Thống Kê
        private void btnNgay_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabThongKe;

            SqlCommand cmd = new SqlCommand("ThongKeDoanhThuTheoNgay", cnn);
            cmd.Parameters.Add("@Ngay", SqlDbType.DateTime).Value = DateTime.Now.ToShortDateString();
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter dscmd = new SqlDataAdapter(cmd);
            DataSet1 ds = new DataSet1();
            dscmd.Fill(ds.DataTable2);
            BaoCaoDT objRpt = new BaoCaoDT();
            objRpt.SetDataSource(ds.Tables[1]);
            ParameterDiscreteValue pdv = new ParameterDiscreteValue();
            pdv.Value = "Thống Kê Doanh Thu Ngày " + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year;
            ParameterValues pv = new ParameterValues();
            pv.Add(pdv);
            objRpt.DataDefinition.ParameterFields["Title"].ApplyCurrentValues(pv);
            crystalReportViewer2.ReportSource = objRpt;
            crystalReportViewer2.Refresh();
        }

        private void btnThang_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("ThongKeDoanhThuTheoThang", cnn);
            cmd.Parameters.Add("@Ngay", SqlDbType.DateTime).Value = DateTime.Now.ToShortDateString();
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter dscmd = new SqlDataAdapter(cmd);
            DataSet1 ds = new DataSet1();
            dscmd.Fill(ds.DataTable2);
            BaoCaoDT objRpt = new BaoCaoDT();
            objRpt.SetDataSource(ds.Tables[1]);
            ParameterDiscreteValue pdv = new ParameterDiscreteValue();
            pdv.Value = "Thống Kê Doanh Thu Tháng " + DateTime.Now.Month + "-" + DateTime.Now.Year;
            ParameterValues pv = new ParameterValues();
            pv.Add(pdv);
            objRpt.DataDefinition.ParameterFields["Title"].ApplyCurrentValues(pv);
            crystalReportViewer2.ReportSource = objRpt;
            crystalReportViewer2.Refresh();
        }

        private void btnNam_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("ThongKeDoanhThuTheoNam", cnn);
            cmd.Parameters.Add("@Ngay", SqlDbType.DateTime).Value = DateTime.Now.ToShortDateString();
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter dscmd = new SqlDataAdapter(cmd);
            DataSet1 ds = new DataSet1();
            dscmd.Fill(ds.DataTable2);
            BaoCaoDT objRpt = new BaoCaoDT();
            objRpt.SetDataSource(ds.Tables[1]);
            ParameterDiscreteValue pdv = new ParameterDiscreteValue();
            pdv.Value = "Thống Kê Doanh Thu Năm " + DateTime.Now.Year;
            ParameterValues pv = new ParameterValues();
            pv.Add(pdv);
            objRpt.DataDefinition.ParameterFields["Title"].ApplyCurrentValues(pv);
            crystalReportViewer2.ReportSource = objRpt;
            crystalReportViewer2.Refresh();
        }
        #endregion

       
    }
}
